<?php

namespace app\admin\controller\record;

use app\common\controller\Backend;
use app\common\model\BehaviorCategory;
use app\common\model\BehaviorRecord;
use app\common\model\Dorm;
use app\common\model\User;
use think\Db;
use think\Exception;
use think\exception\PDOException;

/**
 * 文字点评
 *
 * Class Words
 * User ZhenZiHan
 * Date 2020/3/31
 * @package app\admin\controller\record
 */
class Words extends Backend
{
    /**
     * @var \app\common\model\BehaviorRecord
     */
    protected $model = null;
    protected $searchFields = 'name';
    protected $noNeedRight = ['data', 'detail'];
    protected $schoolLimit = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('BehaviorRecord');
    }

    /**
     * 查看
     */
    public function index()
    {
        return $this->view->fetch();
    }

    public function data()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $type = $this->request->request('type');
            switch ($type) {
                case 'dorm':
                    $key = 'dorm_id';
                    $behavior_category_type = [BehaviorCategory::DORM, BehaviorCategory::DORM_STUDENT];
                    break;
                case 'classes':
                    $key = 'class_id';
                    $behavior_category_type = [BehaviorCategory::CLASSES];
                    break;
                case 'student':
                    $key = 'student_id';
                    $behavior_category_type = [BehaviorCategory::STUDENT];
                    break;
            }

            if (!isset($behavior_category_type)) {
                $result = array("total" => 0, "rows" => []);
                return json($result);
            }

            $total = BehaviorRecord::alias('record')
                ->join('__BEHAVIOR_RECORD_IMAGE__ image', 'image.record_id = record.id')
                ->where($where)
                ->whereIn('record.behavior_category_type', $behavior_category_type)
                ->where(function ($query) {
                    $query->whereNotNull('comment')->whereOr('image.id', '>', 0);
                })
                ->group('record.id')
                ->count();

            $list = BehaviorRecord::alias('record')
                ->join('__BEHAVIOR_RECORD_IMAGE__ image', 'image.record_id = record.id')
                ->where($where)
                ->whereIn('record.behavior_category_type', $behavior_category_type)
                ->where(function ($query) {
                    $query->whereNotNull('comment')->whereOr('image.id', '>', 0);
                })
                ->field("record.id,record.$key,record.comment,record.json_data,count(image.id) image_count")
                ->group("record.id")
                ->limit($offset, $limit)
                ->select();

            if ($list) {
                $list = collection($list)->toArray();
                switch ($type) {
                    case 'dorm':
                        $dorm_ids = array_column($list, 'dorm_id');
                        $dorms = Dorm::whereIn('id', $dorm_ids)
                            ->column('id,num,number,floor,bed_count,bed_used_count', 'id');
                        foreach ($list as $key => $value) {
                            if (isset($dorms[$value['dorm_id']])) {
                                $list[$key]['dorm_floor'] = $dorms[$value['dorm_id']]['floor'];
                                $list[$key]['dorm_used_count'] = $dorms[$value['dorm_id']]['bed_used_count'];
                            }
                        }
                        break;
                    case 'classes':
                        $class_ids = array_column($list, 'class_id');
                        $classes = \app\common\model\Classes::alias('classes')
                            ->join('__SCHOOL__ school', 'school.id = classes.school_id')
                            ->join('__GRADE__ grade', 'grade.id = classes.grade_id')
                            ->join('__TEACHER__ teacher', 'teacher.id = classes.headmaster', 'left')
                            ->join('__USER__ user', 'user.id = teacher.user_id', 'left')
                            ->whereIn('classes.id', $class_ids)
                            ->column('classes.id,classes.name,classes.logo,classes.grade_id,grade.name grade_name,classes.school_id,school.name school_name,classes.headmaster,user.nickname headmaster_name,user.avatar headmaster_avatar', 'classes.id');

                        foreach ($list as $key => $value) {
                            if (isset($classes[$value['class_id']])) {
                                $list[$key]['school_name'] = $classes[$value['class_id']]['school_name'];
                                $list[$key]['grade_name'] = $classes[$value['class_id']]['grade_name'];
                                $list[$key]['class_name'] = $classes[$value['class_id']]['name'];
                                $list[$key]['headmaster_name'] = $classes[$value['class_id']]['headmaster_name'];
                            }
                        }
                        break;
                    case 'student':
                        $student_ids = array_column($list, 'student_id');
                        $students = \app\common\model\Student::alias('student')
                            ->join('__CLASSES__ classes', 'classes.id = student.class_id')
                            ->join('__GRADE__ grade', 'grade.id = student.grade_id')
                            ->join('__SCHOOL__ school', 'school.id = student.school_id')
                            ->whereIn('student.id', $student_ids)
                            ->column('student.id,student.number,student.name,student.gender,student.avatar,school.name school_name,grade.name grade_name,classes.name class_name', 'student.id');
                        if ($students) {
                            foreach ($students as $key => $value) {
                                $students[$key]['gender_text'] = User::getGender($value['gender']);
                            }
                        }
                        foreach ($list as $key => $value) {
                            if (isset($students[$value['student_id']])) {
                                $list[$key]['school_name'] = $students[$value['student_id']]['school_name'];
                                $list[$key]['name'] = $students[$value['student_id']]['name'];
                                $list[$key]['gender_text'] = $students[$value['student_id']]['gender_text'];
                            }
                        }
                        break;
                }
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
    }

    // 详细信息
    public function detail()
    {
        $ids = $this->request->request('ids');
        $type = $this->request->request('type');

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            switch ($type) {
                case 'dorm':
                    $behavior_category_type = [BehaviorCategory::DORM, BehaviorCategory::DORM_STUDENT];
                    break;
                case 'classes':
                    $behavior_category_type = [BehaviorCategory::CLASSES];
                    break;
                case 'student':
                    $behavior_category_type = [BehaviorCategory::STUDENT];
                    break;
                default:
                    return json(["total" => 0, "rows" => []]);
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = BehaviorRecord::alias('record')
                ->join('__BEHAVIOR_RECORD_IMAGE__ image', 'image.record_id = record.id')
                ->where('record.id', $ids)
                ->whereIn('record.behavior_category_type', $behavior_category_type)
                ->where($where)
                ->count();

            $list = BehaviorRecord::alias('record')
                ->join('__BEHAVIOR_RECORD_IMAGE__ image', 'image.record_id = record.id', 'right')
                ->where('record.id', $ids)
                ->whereIn('record.behavior_category_type', $behavior_category_type)
                ->where($where)
                ->field("image.id,record.behavior_category_type,record.record_user_id,record.record_user_group,record.created_at,record.json_data,image.url")
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            return json(["total" => $total, "rows" => $list]);
        }
        $this->assignconfig("admin", ['ids' => $ids, 'type' => $type]);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $model = model('BehaviorRecordDetail');
            $list = $model->where('id', 'in', $ids)->select();
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
